package edu.zjut.hjg.saas.web.controller.home;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_TENANT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.zjut.hjg.saas.biz.model.Tenant;
import edu.zjut.hjg.saas.biz.service.TenantService;
import edu.zjut.hjg.saas.biz.service.exception.ServiceException;
import edu.zjut.hjg.saas.common.annotation.CookieSessionOut;
import edu.zjut.hjg.saas.web.model.TenantSession;
import edu.zjut.hjg.saas.web.model.form.RegisterTenantForm;

/**
 * 注册租户
 * 
 * @author hjg
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    private static final Log log = LogFactory.getLog(RegisterController.class);

    @Autowired
    private TenantService    tenantService;

    @RequestMapping("index.htm")
    public void index(
                      Model model,
                      @RequestHeader(value = "referer", required = false, defaultValue = "/index.htm") String referer) {
        RegisterTenantForm registerTenant = new RegisterTenantForm();
        model.addAttribute("toUrl", referer);
        model.addAttribute("tenantForm", registerTenant);
    }

    @RequestMapping(value = "doRegister.htm", method = RequestMethod.POST)
    @CookieSessionOut(SESSION_NAME_TENANT)
    public String doRegister(@Valid @ModelAttribute("tenantForm") RegisterTenantForm tenantForm,
                             BindingResult result, @RequestParam("toUrl") String toUrl, Model model) {
        model.addAttribute("toUrl", toUrl);
        if (result.hasErrors()) {
            return "register/index";
        }
        try {
            int id = tenantService.create(getTenant(tenantForm));
            TenantSession session = new TenantSession();
            session.setId(id);
            session.setLoginId(tenantForm.getLoginId());
            session.setName(tenantForm.getName());
            model.addAttribute(SESSION_NAME_TENANT, session);
        } catch (ServiceException e) {
            log.error(e.getMessage() + ", " + e.getErrorMessage(), e);
            result.reject("error.register.form", e.getErrorMessage());
            return "register/index";
        }
        return "register/success";
    }

    @RequestMapping(value = "loginIdExist.htm")
    @ResponseBody
    public Map<String, Object> loginIdExist(@RequestParam("loginId") String loginId) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("exist", tenantService.loginIdExist(loginId));
        return model;
    }

    private Tenant getTenant(RegisterTenantForm tenantForm) {
        Tenant tenant = new Tenant();
        tenant.setBalance(0.00);
        tenant.setLoginId(tenantForm.getLoginId());
        tenant.setEmail(tenantForm.getEmail());
        tenant.setName(tenantForm.getName());
        tenant.setPassword(tenantForm.getPassword());
        tenant.setRegisterTime(new Date());
        if (StringUtils.isNotBlank(tenantForm.getContact().trim())) {
            tenant.setContact(tenantForm.getContact().trim());
        }
        if (StringUtils.isNotBlank(tenantForm.getPhone().trim())) {
            tenant.setPhone(tenantForm.getPhone().trim());
        }
        return tenant;
    }
}
